package com.sport.video.gateway.filter;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sport.video.common.dto.common.ResponseParams;
import com.sport.video.common.enums.RespEnum;
import com.sport.video.gateway.constant.FilterContant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 错误过滤器
 *@Author Gred
 *@Date 2019/3/4 16:37
 *@version 1.0
 **/
@Slf4j
public class PostFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        int stausCode = ctx.getResponseStatusCode();
        //return false;
        return HttpStatus.OK.value() != stausCode;
    }

    @Override
    public Object run(){
        RequestContext ctx = RequestContext.getCurrentContext();
        int code = ctx.getResponseStatusCode();
        ResponseParams response = new ResponseParams();
        response.setResultCode(code);
        response.setResultMsg(JSON.toJSONString(ctx.getThrowable()));
        response.setTimestamp(DateUtil.current(false));

        HttpServletResponse servletResponse = ctx.getResponse();
        try {
            ServletOutputStream outputStream = servletResponse.getOutputStream();
            outputStream.write(JSON.toJSONString(response).getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
